package cn.yq.aio.ui.main.chengfen;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.yq.aio.base.MyApp;
import cn.yq.aio.databinding.FragmentChengFenBinding;
import cn.yq.aio.utils.BleUtils;
import cn.yq.aio.utils.recycler.GridItemDecoration;
import cn.yq.aio.utils.recycler.TShow;

/**
 * @AUTHOR YangLu
 * @Time 2021-03-25
 * @todo 人体成分
 */
public class ChengFenFragment extends Fragment {

    public ChengFenFragment() {
    }

    public static ChengFenFragment newInstance() {
        ChengFenFragment chengFenFragment = new ChengFenFragment();
        return chengFenFragment;
    }

    FragmentChengFenBinding binding;
    ChengfenAdapter adapter;

    final String zhiFangProductName = "bodyslim";
    UsbDevice zhiFangDevice = null;
    UsbManager usbManager;
    UsbPermissionReceiver receiver;
    UsbEndpoint usbEndpointIn = null, usbEndpointOut = null;
    UsbDeviceConnection connection;

    Thread readThread;
    boolean stop = false;


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentChengFenBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.rightMain.titleRightMainFrg.setText("人体成分测量");
        binding.rightMain.measureRightMainFrg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    checkStart();
                } catch (Exception e) {
                    e.printStackTrace();
                    TShow.show(e.toString());
                }
            }
        });
        binding.getRoot().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (binding.tipsChengFenFrg.getVisibility() == View.VISIBLE) {
                    binding.tipsChengFenFrg.setVisibility(View.GONE);
                }
                return false;
            }
        });

        binding.recyclerChengFenFrg.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                if (binding.tipsChengFenFrg.getVisibility() == View.VISIBLE) {
                    binding.tipsChengFenFrg.setVisibility(View.GONE);
                    return true;
                }
                return false;
            }

            @Override
            public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {

            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

            }
        });

        adapter = new ChengfenAdapter();
        binding.recyclerChengFenFrg.setLayoutManager(new GridLayoutManager(getContext(), 2));
        binding.recyclerChengFenFrg.setAdapter(adapter);
        binding.recyclerChengFenFrg.addItemDecoration(new GridItemDecoration(MyApp.dp2px(10),
                MyApp.dp2px(10)));

        List<ChengFenBean> list = new ArrayList<>();
        list.add(new ChengFenBean("肌肉重", "Kg", "一般", "13.5", "142.5", "正常范围：12.5~162.5Kg"));
        list.add(new ChengFenBean("肌肉重", "Kg", "一般", "13.5", "142.5", "正常范围：12.5~162.5Kg"));
        adapter.setLists(list);
    }

    private void checkStart() {
        usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        if (deviceList.size() == 0) {
            showTips("没有监测到usb设备");
            return;
        }
        for (Map.Entry<String, UsbDevice> temp : deviceList.entrySet()) {
            Log.e(getClass().getSimpleName(), "name = " + temp.getKey() +
                    " " + temp.getValue().getProductName());
            if (TextUtils.equals(zhiFangProductName, temp.getValue().getProductName())) {
                zhiFangDevice = temp.getValue();
            }
        }
        if (zhiFangDevice == null) {
            showTips("没有查询到脂肪仪");
            return;
        }
        if (!usbManager.hasPermission(zhiFangDevice)) {
            receiver = new UsbPermissionReceiver();
            Intent it = new Intent("action_device_permission");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, it, 0);
            IntentFilter intentFilter = new IntentFilter("action_device_permission");
            getActivity().registerReceiver(receiver, intentFilter);
            usbManager.requestPermission(zhiFangDevice, pendingIntent);
            showTips("请求权限");
            return;
        }
        open();
    }

    private class UsbPermissionReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (TextUtils.equals(intent.getAction(), "action_device_permission")) {
                showTips("授权成功");
                open();
            }
        }
    }

    private void open() {
        showTips("准备连接...");
        UsbInterface usbInterface = zhiFangDevice.getInterface(0);

        StringBuffer sb = new StringBuffer();

        for (int index = 0; index < usbInterface.getEndpointCount(); index++) {
            UsbEndpoint point = usbInterface.getEndpoint(index);
            sb.append("point = " + point.getType() + "   diraction = " + point.getDirection() +
                    "\n");
            if (point.getType() == UsbConstants.USB_ENDPOINT_XFERTYPE_MASK) {
                if (point.getDirection() == UsbConstants.USB_DIR_IN) {
                    usbEndpointIn = point;
                } else if (point.getDirection() == UsbConstants.USB_DIR_OUT) {
                    usbEndpointOut = point;
                }
            }
        }
        showTips(sb.toString());

        if (usbEndpointOut == null) {
            showTips("获取写入失败");
            return;
        }
        if (usbEndpointIn == null) {
            showTips("获取读取失败");
            return;
        }
        showTips("发起连接...");
        connection = usbManager.openDevice(zhiFangDevice);
        byte[] in = new byte[20];

        connection.bulkTransfer(usbEndpointOut, ZhiFangUtils.getUUID,
                ZhiFangUtils.getUUID.length, 1000 * 3);
        connection.bulkTransfer(usbEndpointIn, in, in.length, 1000 * 30);
        Log.e(getClass().getSimpleName(), BleUtils.byteToHex(in));


        connection.bulkTransfer(usbEndpointOut, ZhiFangUtils.getVersion,
                ZhiFangUtils.getVersion.length, 1000 * 3);
        connection.bulkTransfer(usbEndpointIn, in, in.length, 1000 * 30);
        Log.e(getClass().getSimpleName(), BleUtils.byteToHex(in));
    }


    class ReadCallBack implements Handler.Callback {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            return false;
        }
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
//            final byte[] in = new byte[20];
//            while (!stop) {
//                try {
//                    Log.e("read: ", "usbEndpointIn = " + usbEndpointIn);
//                    if (usbEndpointIn == null) {
//                        Thread.sleep(1000);
//                    }
//                    Log.e("read: ", "start read");
//                    connection.bulkTransfer(usbEndpointIn, in, in.length, 1000 * 30);
//                    Log.e("read: ", BleUtils.byteToHex(in));
//                    MyApp.getInstance().handler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            showTips(BleUtils.byteToHex(in));
//                        }
//                    });
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        stop = false;
        readThread = new Thread(runnable);
        readThread.start();
    }

    @Override
    public void onStop() {
        super.onStop();
        stop = true;
        if (readThread != null)
            readThread.interrupt();
        readThread = null;
    }

    private void showTips(String msg) {
        binding.tipsChengFenFrg.setVisibility(View.VISIBLE);
        binding.tipsChengFenFrg.setText(msg);
    }

    private void hideTips() {
        binding.tipsChengFenFrg.setVisibility(View.GONE);
    }
}
